package com.night.permManager.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.night.common.entity.ResultVo;
import com.night.common.entity.StatusCode;
import com.night.common.entity.account.User;
import com.night.common.entity.administration.Teacher;
import com.night.common.entity.role.*;
import com.night.common.entity.student.Student;
import com.night.common.groupInterface.AddGroup;
import com.night.common.groupInterface.AlterGroup;
import com.night.permManager.jwtUtil.JwtUtils;
import com.night.permManager.service.MenuPermService;
import com.night.permManager.service.MenuService;
import com.night.permManager.service.RoleMenuMidService;
import com.night.permManager.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: RoleController
 * @Description: //TODO
 * @author: dz
 * @date: 2022-08-31-15:25
 */
@RestController
@RequestMapping("/api/v1/role")
@Slf4j
public class RoleController {

    @Autowired
    RoleService roleService;

    @Autowired
    MenuService menuService;

    @Autowired
    MenuPermService menuPermService;

    @Autowired
    RoleMenuMidService roleMenuMidService;

    @Resource
    JwtUtils jwtUtils;

    /**
     * 可以用于产生列表和产生树
     *
     * @return
     */
    @PostMapping("/list")
    public ResultVo<?> list() {
        List<Role> roles = roleService.list();
        return new ResultVo<>(roles);
    }

    /**
     * 修改权限菜单
     *
     * @param menuPerm
     * @return
     */
    @PostMapping("/menuPerm/update")
    public ResultVo<?> updateMenuPerm(@RequestBody MenuPerm menuPerm) {
        menuPermService.updateById(menuPerm);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/menuPerm/list")

    public ResultVo<?> getMenuPerm() {
        return new ResultVo<>(menuPermService.list());
    }

    @PostMapping("/menuPerm/add")
    public ResultVo<?> addMenuPerm(@RequestBody MenuPerm menuPerm) {
        menuPermService.save(menuPerm);
        return ResultVo.SUCCESS;
    }

    /**
     * 通过角色id查找权限列表，用于权限树的选择（？选择返回权限id的数组集合）
     *
     * @param roleId
     * @return
     */
    @PostMapping("/getPermByRoleId")
    public ResultVo<?> getPermByRoleId(int roleId) {
        return new ResultVo<>(menuPermService.getByRoleId(roleId));
//        return new ResultVo<>(new ArrayList<>());
    }

    @PostMapping("/add")
    public ResultVo<?> add(@RequestBody @Validated(AddGroup.class) RoleVo roleVo) {
        roleService.save(roleVo.getRole());
        System.out.println(roleVo);
        QueryWrapper<RoleMenuMid> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleVo.getRole().getId());
        roleMenuMidService.remove(wrapper);
        List<RoleMenuMid> roleMenuMidList = new ArrayList<>();
        for (int i : roleVo.getMenuPermIds()) {
            RoleMenuMid roleMenuMid = new RoleMenuMid();
            roleMenuMid.setRoleId(roleVo.getRole().getId());
            roleMenuMid.setMenuId(i);
            roleMenuMidList.add(roleMenuMid);
        }
        roleMenuMidService.saveBatch(roleMenuMidList);
        return new ResultVo<>(roleVo.getRole().getId());
    }

    @PostMapping("/update")
    @Transactional
    public ResultVo<?> update(@RequestBody @Validated(AlterGroup.class) RoleVo roleVo) {
        roleService.updateById(roleVo.getRole());
        QueryWrapper<RoleMenuMid> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleVo.getRole().getId());
        roleMenuMidService.remove(wrapper);
        List<RoleMenuMid> roleMenuMidList = new ArrayList<>();
        for (int i : roleVo.getMenuPermIds()) {
            RoleMenuMid roleMenuMid = new RoleMenuMid();
            roleMenuMid.setRoleId(roleVo.getRole().getId());
            roleMenuMid.setMenuId(i);
            roleMenuMidList.add(roleMenuMid);
        }
        roleMenuMidService.saveBatch(roleMenuMidList);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/delete")
    @Transactional
    public ResultVo<?> delete(int roleId) {
        QueryWrapper<RoleMenuMid> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        roleMenuMidService.remove(wrapper);
        roleService.removeById(roleId);
        return ResultVo.SUCCESS;
    }

    @PostMapping("menu/list")
    public ResultVo<?> MenuList(HttpServletRequest request) {
        QueryWrapper<Menu> menuWrapper = new QueryWrapper<>();
        String jwt = request.getHeader("jwt");
        Object roleId = JwtUtils.getInfo(jwt, "roleId");
        String[] menuType = {"m", "c"};
        menuWrapper.in("ss_menu.menu_type", menuType);
        menuWrapper.eq("ss_role_menu.role_id", roleId);
        menuWrapper.orderByAsc("ss_menu.order_num");
        List<Menu> menuList = menuService.menuPage(new Page<>(1, Integer.MAX_VALUE), menuWrapper).getRecords();
        List<Menu> menuBack = new ArrayList<>();
        for (Menu menu : menuList) {
            if (menu.getParentId() == 0) {
                List<Menu> menus = new ArrayList<>();
                for (Menu menu_temp : menuList) {
                    if (menu_temp.getParentId().equals(menu.getId())) {
                        menus.add(menu_temp);
                    }
                    menu.setSubMenu(menus);
                }
                menuBack.add(menu);
            }
        }
        return new ResultVo<>(menuBack);
    }

    @PostMapping("/login")
   public ResultVo<?> getUserByAccount(@RequestBody User user, HttpServletResponse response){
        System.out.println(user);
        //1表示学生，2表示教师
        if ("1".equals(user.getType())){
            Student student = roleService.getStudent(user.getAccountNumber());
            System.out.println("student登录"+student);
            if (student == null || !student.getPassword().equals(user.getPassword().trim())){
                return new ResultVo<>(StatusCode.ACCOUNT_FAIL);
            }
            user.setRoleId(3);
            user.setAccountId(student.getId());
        }else if("2".equals(user.getType())) {
            Teacher teacher = roleService.getTeacher(user.getAccountNumber());
            System.out.println("teacher登录"+teacher);
            if (teacher == null || !teacher.getPassword().equals(user.getPassword().trim())){
                return new ResultVo<>(StatusCode.ACCOUNT_FAIL);
            }
            user.setRoleId(2);
            user.setAccountId(teacher.getId());
        }
        response.addHeader("jwt", jwtUtils.creatJWT(user.getAccountId(), user.getAccountNumber(), user.getRoleId(), user.getType()));
        return ResultVo.SUCCESS;
    }
}
